import { Button, Form, FormInstance, Input, Select, Space, TreeSelect } from 'antd';
import { useCallback, useState } from 'react';
import { ColumnsRenderFun, DictionaryRenderFun, formatDecimal } from '../../Acommon';
import pageStyles from '@/common/pageLayout.less';
import { getLoadMapList, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { RegularExpression } from '@/common/constVariable';

/**
 * @getMaterialModalLandColumns 步骤条第二步 材料弹窗配置
 */
export const getMaterialModalLandColumns = (uploadForm: any): Record<string, any>[] => {
  /**保存上级岗位搜索输入框的值*/
  const [treeSearch, setTreeSearch] = useState<string>('');

  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`,
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`,
  ];
  const { loadMapInfo: loadMdicMapList, mapLoading } = getLoadMapList(loadMdicIds);

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          // disabled: !item?.pID,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  /** 材料类型选中*/
  const selectMaterialType = (selectedKeys: any, e: any, index: number) => {
    handleMaterialCombined(uploadForm, index, selectedKeys, 'materialType');
  };

  /** 规格要求（参数）改变时 */
  const handleChangeSpecInfo = (e: any, index: number) => {
    handleMaterialCombined(uploadForm, index, e?.target?.value, 'specInfo');
  };

  /** 处理数据 */
  const handleMaterialCombined = (formName: FormInstance, fomIndex: number, currentValue: any, formType: string) => {
    const materialFormValues: Record<string, any>[] = formName?.getFieldValue('table');
    // materialFormValues[fomIndex]['materialNum'] = currentValue;

    if (formType == 'materialType') {
      materialFormValues[fomIndex]['materialNum'] = currentValue + materialFormValues[fomIndex]['specInfo']?.slice(0, 6);
    } else if (formType == 'specInfo') {
      materialFormValues[fomIndex]['materialNum'] = materialFormValues[fomIndex]['materialType'] + currentValue;
    }

    formName?.setFieldsValue({
      table: materialFormValues,
    });
  };

  // 获取搜索框输入的值
  const treeSearchValue = useCallback(
    (valText: string) => {
      setTreeSearch(valText);
    },
    [treeSearch],
  );

  return [
    {
      title: '材料类型',
      dataIndex: 'materialTypeName',
      key: 'materialTypeName',
      visible: true,
      width: 180,
      sorter: (a: any, b: any) => (a?.materialType > b?.materialType ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'materialType']}
            rules={[
              {
                required: true,
                message: '请选择材料类型',
              },
            ]}
          >
            <TreeSelect
              placeholder="请选择材料类型"
              showSearch={true}
              loading={mapLoading}
              treeNodeFilterProp={'searchTitle'}
              treeData={orgTreeData(loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`])}
              onSearch={treeSearchValue}
              onSelect={(selectedKeys, e) => {
                selectMaterialType(selectedKeys, e, index);
              }}
            />
          </Form.Item>
        );
      },
    },
    {
      title: '材料编码',
      dataIndex: 'materialNum',
      key: 'materialNum',
      visible: true,
      width: 150,
      sorter: (a: any, b: any) => (a?.materialNum > b?.materialNum ? 1 : -1),
      render: (text: string | null) => ColumnsRenderFun({ text, wordNum: 100, isTooltip: true }),
    },
    {
      title: '材料名称',
      dataIndex: 'fullName',
      key: 'fullName',
      visible: true,
      width: 150,
      sorter: (a: any, b: any) => (a?.fullName > b?.fullName ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'fullName']}
            rules={[
              {
                required: true,
                message: '请输入材料名称',
              },
            ]}
          >
            <Input placeholder="请输入材料名称" allowClear />
          </Form.Item>
        );
      },
    },
    {
      title: '供货分类',
      dataIndex: 'supplyTypeName',
      key: 'supplyTypeName',
      visible: true,
      width: 180,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.supplyType > b?.supplyType ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'supplyType']}
            rules={[
              {
                required: true,
                message: '请选择供货分类',
              },
            ]}
          >
            <Select placeholder="请选择供货分类" loading={mapLoading}>
              {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]?.map((item: any) => {
                return (
                  <Select.Option key={item?.id} value={item?.id}>
                    {item?.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        );
      },
    },
    {
      title: '规格要求（参数）',
      dataIndex: 'specInfo',
      key: 'specInfo',
      visible: true,
      width: 185,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.specInfo > b?.specInfo ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'specInfo']}
            rules={[
              {
                required: true,
                message: '请输入规格要求（参数）',
              },
            ]}
          >
            <Input
              placeholder="请输入规格要求（参数）"
              allowClear
              onChange={(e: any) => {
                handleChangeSpecInfo(e, index);
              }}
            />
          </Form.Item>
        );
      },
    },
    {
      title: '规格型号',
      dataIndex: 'modelNum',
      key: 'modelNum',
      visible: true,
      width: 150,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.modelNum > b?.modelNum ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'modelNum']}
            rules={[
              {
                required: true,
                message: '请输入规格型号',
              },
            ]}
          >
            <Input placeholder="请输入规格型号" allowClear />
          </Form.Item>
        );
      },
    },
    {
      title: '参考单价（元）',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      visible: true,
      width: 180,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.unitPrice > b?.unitPrice ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'unitPrice']}
            rules={[
              {
                required: true,
                message: '请输入参考单价（元）',
              },
              {
                pattern: RegularExpression?.floatNumber,
                message: '参考单价只能填数字！',
              },
              {
                pattern: /^\d+(\.\d{1,2})?$/,
                message: '最多可保留两位小数！',
              },
            ]}
          >
            <Input placeholder="请输入参考单价（元）" allowClear addonAfter={'元'} />
          </Form.Item>
        );
      },
    },
    {
      title: '量化单位',
      dataIndex: 'unitBusinessName',
      key: 'unitBusinessName',
      visible: true,
      width: 180,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.unitBusiness > b?.unitBusiness ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'unitBusiness']}
            rules={[
              {
                required: true,
                message: '请选择量化单位',
              },
            ]}
          >
            <Select placeholder="请选择量化单位" loading={mapLoading}>
              {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]?.map((item: any) => {
                return (
                  <Select.Option key={item?.id} value={item?.id}>
                    {item?.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        );
      },
    },
    {
      title: '材料简介',
      dataIndex: 'paramsInfo',
      key: 'paramsInfo',
      visible: true,
      width: 180,
      unDrag: false,
      sorter: (a: any, b: any) => (a?.paramsInfo > b?.paramsInfo ? 1 : -1),
      render: (_text: string, _record: any, index: any) => {
        return (
          <Form.Item
            name={['table', index, 'paramsInfo']}
            rules={[
              {
                required: true,
                message: '请输入材料简介',
              },
            ]}
          >
            <Input placeholder="请输入材料简介" allowClear />
          </Form.Item>
        );
      },
    },
  ];
};
